package com.cy.store.Service.Impl;

import com.cy.store.Entity.User;
import com.cy.store.Mapper.UserMapper;
import com.cy.store.Service.Ex.*;
import com.cy.store.Service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service
public class IUserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;


    //注册
    @Override
    public void reg(User user) throws InsertException, UsernameDuplicatedException {
        //通过user参数来获取传递过来的username
        String username = user.getUsername();
        //调用mapper的findByUsername(username)判断用户是否被注册过了
        User result = userMapper.findUserByUserName(username);
        //判断结果集是否为null,不为null的话则需抛出用户名被占用的异常
        if (result != null) {
            //抛出异常
            throw new UsernameDuplicatedException("用户名被占用");
        }

        /**
         * 密码加密处理作用:
         * 1.后端不再能直接看到用户的密码2.忽略了密码原来的强度,提升了数据安全性
         * 密码加密处理的实现:
         * 串+password+串->交给md5算法连续加密三次
         * 串就是数据库字段中的盐值,是一个随机字符串
         */
        String oldPassword = user.getPassword();
        //1.随机生成一个盐值(大写的随机字符串)
        String salt = UUID.randomUUID().toString().toUpperCase();
        //2.将密码和盐值作为一个整体进行加密处理
        String md5Password = getMD5Password(oldPassword, salt);
        //3.将盐值保存到数据库
        user.setSalt(salt);
        //4.将加密之后的密码重新补全设置到user对象当中
        user.setPassword(md5Password);

        //补全数据:is_delete设置为0
        user.setIsDelete(0);
        //补全数据:四个日志字段信息
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);


        //执行注册业务功能的实现
        Integer rows = userMapper.insert(user);
        if (rows != 1) {
            throw new InsertException("在用户注册过程中产生了未知的异常");
        }
    }



    /**
     * 登录
     * @param username
     * @param password
     * @return
     * @throws UsernameDuplicatedException
     * @throws InsertException
     * @throws UserNotFoundException
     * @throws PasswordNotMatchException
     */
    @Override
    public User login(String username, String password) throws UsernameDuplicatedException, InsertException, UserNotFoundException, PasswordNotMatchException {
        //根据用户名来查询用户的数据时候存在，如果不存在则抛出异常
        User user= userMapper.findUserByUserName(username);
        if(user==null){
            throw new UserNotFoundException("用户数据不存在");
        }
        //检测密码是否匹配
        //1.先获取到数据库中的加密后的密码
        String oldPassword = user.getPassword();
        //2.和用户传递过来的密码进行比较
            //2.1 先获取盐值：上一次注册时自动生成盐值
            String salt = user.getSalt();
            //2.2 将用户传递来的密码安相同的md5加密算法进行加密
            String newMd5Password = getMD5Password(password, salt);
        //3.将密码进行比较

        //判断用户是否注销
        if(user.getIsDelete()==1){
            throw new UserNotFoundException("用户已注销");
        }
        if(!oldPassword.equals(newMd5Password)){
            throw new PasswordNotMatchException("密码错误");
        }

        User newUser = new User();
        newUser.setUsername(user.getUsername());
        newUser.setUid(user.getUid());
        newUser.setAvatar(user.getAvatar());
        //返回的数据时为了辅助其他页面做数据展示使用（uid,username）
        return newUser;
    }

    /**
     * 自定义md5加密
     * @param password
     * @param salt
     * @return
     */
    //自定义一个md5加密操作
    private String getMD5Password(String password,String salt) {
        for (int i = 0; i < 3; i++) {
            //md5加密算法方法的调用
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }

    /**
     * 修改用户密码
     * @param uid
     * @param username
     * @param oldpassword
     * @param newpassword
     */
    @Override
   public void changePassword(Integer uid,String username,String oldpassword
            ,String newpassword) throws UserNotFoundException, PasswordNotMatchException, UpdateException {
        User result = userMapper.findByUid(uid);
        if(result==null||result.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }

        //原始密码和数据库中的密码比较
        String oldMD5password = getMD5Password(oldpassword, result.getSalt());

        //密码与原密码不匹配
        if(!result.getPassword().equals(oldMD5password)){
            throw new PasswordNotMatchException("密码错误");
        }
        //原密码输入正确，将新的密码设置到数据库，将新密码继续加密
        else{
            String newmMD5Password = getMD5Password(newpassword, result.getSalt());
            Integer rows = userMapper.updatePasswordByUid(uid, newmMD5Password, username, new Date());
            if (rows != 1) {
                throw new UpdateException("更新数据时产生未知的异常");
            }
        }


    }

    @Override
    public User getByUid(Integer uid) throws UserNotFoundException {
        User result=userMapper.findByUid(uid);
        if(result==null||result.getIsDelete()==1){
            throw new UserNotFoundException("该用户不存在");
        }
        User user=new User();
        user.setUid(uid);
        user.setUsername(result.getUsername());
        user.setEmail(result.getEmail());
        user.setPhone(result.getPhone());
        user.setGender(result.getGender());
        return user;
    }

    @Override
    public void changeInfo(Integer uid, String name, User user) throws UserNotFoundException, UpdateException {
       User result= userMapper.findByUid(uid);
       if(result==null||result.getIsDelete()==1){
           throw new UserNotFoundException("该用户不存在");
       }
       user.setUid(uid);
       user.setModifiedUser(name);
       user.setModifiedTime(new Date());
       Integer rows=userMapper.updateInfoByUid(user);
       if(rows!=1){
           throw new UpdateException("更新时出现未知的异常");
       }
    }

    /**
     * 修改用户头像
     * @param uid
     * @param avatar
     * @param username
     * @throws UserNotFoundException
     * @throws UpdateException
     */
    @Override
    public void changeAvatar(Integer uid, String avatar, String username) throws UserNotFoundException, UpdateException {
        //查询当前用户的数据是否存在、
        User result= userMapper.findByUid(uid);
        if(result==null||result.getIsDelete()==1){
            throw new UserNotFoundException();
        }
        Integer row=userMapper.updateAvatarByUid(uid,avatar,username,new Date());
        if(row!=1){
            throw new UpdateException("更新用户头像时产生了未知的异常");
        }
    }
}
